use tauri::State;
use serde::{Deserialize, Serialize};
use tracing::{info, error, debug};
use uuid::Uuid;
use chrono;

use crate::database::DatabaseManager;
use crate::database::schema::SocialAccount;
use crate::error::{AppError, Result as AppResult};

#[derive(Debug, Serialize, Deserialize)]
pub struct AccountResponse {
    pub id: String,
    pub platform: String,
    pub username: String,
    pub display_name: Option<String>,
    pub email: Option<String>,
    pub status: String,
    pub assigned_device_id: Option<String>,
    pub followers: Option<u64>,
    pub following: Option<u64>,
    pub posts: Option<u64>,
    pub last_login: Option<String>,
    pub last_activity: Option<String>,
    pub created_at: String,
    pub updated_at: String,
}

impl From<SocialAccount> for AccountResponse {
    fn from(account: SocialAccount) -> Self {
        // 解析 account_info JSON 字段
        let account_info = account.account_info.as_ref()
            .and_then(|info| serde_json::from_str::<serde_json::Value>(info).ok());
        
        Self {
            id: account.id,
            platform: account.platform,
            username: account.username,
            display_name: account.display_name,
            email: account.email,
            status: account.status,
            assigned_device_id: account.assigned_device_id,
            followers: account_info.as_ref()
                .and_then(|info| info.get("followers_count"))
                .and_then(|v| v.as_u64()),
            following: account_info.as_ref()
                .and_then(|info| info.get("following_count"))
                .and_then(|v| v.as_u64()),
            posts: account_info.as_ref()
                .and_then(|info| info.get("posts_count"))
                .and_then(|v| v.as_u64()),
            last_login: account.last_login.map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string()),
            last_activity: account.last_activity.map(|dt| dt.format("%Y-%m-%d %H:%M:%S").to_string()),
            created_at: account.created_at.format("%Y-%m-%d %H:%M:%S").to_string(),
            updated_at: account.updated_at.format("%Y-%m-%d %H:%M:%S").to_string(),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CreateAccountRequest {
    pub platform: String,
    pub username: String,
    pub display_name: Option<String>,
    pub email: Option<String>,
    pub credentials: serde_json::Value,
}

/// 获取账号列表
#[tauri::command]
pub async fn get_accounts(
    db: State<'_, DatabaseManager>
) -> Result<Vec<AccountResponse>, String> {
    info!("Fetching accounts list");
    
    match db.get_accounts().await {
        Ok(accounts) => {
            let account_responses: Vec<AccountResponse> = accounts
                .into_iter()
                .map(AccountResponse::from)
                .collect();
            
            debug!("Retrieved {} accounts", account_responses.len());
            Ok(account_responses)
        }
        Err(e) => {
            error!("Failed to fetch accounts: {}", e);
            Err(format!("Failed to fetch accounts: {}", e))
        }
    }
}

/// 根据平台获取账号列表
#[tauri::command]
pub async fn get_accounts_by_platform(
    platform: String,
    db: State<'_, DatabaseManager>
) -> Result<Vec<AccountResponse>, String> {
    info!("Fetching accounts for platform: {}", platform);
    
    match db.get_accounts_by_platform(&platform).await {
        Ok(accounts) => {
            let account_responses: Vec<AccountResponse> = accounts
                .into_iter()
                .map(AccountResponse::from)
                .collect();
            
            debug!("Retrieved {} accounts for platform {}", account_responses.len(), platform);
            Ok(account_responses)
        }
        Err(e) => {
            error!("Failed to fetch accounts for platform {}: {}", platform, e);
            Err(format!("Failed to fetch accounts: {}", e))
        }
    }
}

/// 创建新账号
#[tauri::command]
pub async fn create_account(
    request: CreateAccountRequest,
    db: State<'_, DatabaseManager>
) -> Result<String, String> {
    info!("Creating account: {}@{}", request.username, request.platform);
    
    let account = SocialAccount {
        id: uuid::Uuid::new_v4().to_string(),
        platform: request.platform,
        username: request.username,
        display_name: request.display_name,
        email: request.email,
        encrypted_credentials: serde_json::to_string(&request.credentials).unwrap().into_bytes(),
        credential_type: "password".to_string(),
        account_info: None,
        security_settings: None,
        operation_settings: None,
        assigned_device_id: None,
        status: "inactive".to_string(),
        last_login: None,
        last_activity: None,
        login_failures: 0,
        created_at: chrono::Utc::now().naive_utc(),
        updated_at: chrono::Utc::now().naive_utc(),
    };
    
    let account_id = account.id.clone();
    match db.create_account(&account).await {
        Ok(_) => {
            info!("Account created successfully: {}", account_id);
            Ok(account_id)
        }
        Err(e) => {
            error!("Failed to create account: {}", e);
            Err(format!("Failed to create account: {}", e))
        }
    }
}

/// 分配账号到设备
#[tauri::command]
pub async fn assign_account_to_device(
    account_id: String,
    device_id: String,
    db: State<'_, DatabaseManager>
) -> Result<(), String> {
    info!("Assigning account {} to device {}", account_id, device_id);
    
    match db.assign_account_to_device(&account_id, &device_id).await {
        Ok(_) => {
            info!("Account assigned successfully");
            Ok(())
        }
        Err(e) => {
            error!("Failed to assign account: {}", e);
            Err(format!("Failed to assign account: {}", e))
        }
    }
}

/// 账号登录
#[tauri::command]
pub async fn login_account(
    account_id: String,
    db: State<'_, DatabaseManager>
) -> Result<(), String> {
    info!("Logging in account: {}", account_id);
    
    // TODO: 实现实际的登录逻辑
    // 这里应该包括 WebDriver 自动化登录等
    
    match db.update_account_last_login(&account_id).await {
        Ok(_) => {
            info!("Account logged in successfully: {}", account_id);
            Ok(())
        }
        Err(e) => {
            error!("Failed to login account: {}", e);
            // 增加登录失败计数
            // TODO: implement increment_login_failures method
            Err(format!("Failed to login account: {}", e))
        }
    }
}

/// 账号登出
#[tauri::command]
pub async fn logout_account(
    account_id: String,
    db: State<'_, DatabaseManager>
) -> Result<(), String> {
    info!("Logging out account: {}", account_id);
    
    // TODO: 实现实际的登出逻辑
    
    // 更新账号状态为非活跃
    match db.update_device_status(&account_id, "inactive").await {
        Ok(_) => {
            info!("Account logged out successfully: {}", account_id);
            Ok(())
        }
        Err(e) => {
            error!("Failed to logout account: {}", e);
            Err(format!("Failed to logout account: {}", e))
        }
    }
}

/// 验证账号状态
#[tauri::command]
pub async fn verify_account(
    account_id: String,
    db: State<'_, DatabaseManager>
) -> Result<bool, String> {
    info!("Verifying account: {}", account_id);
    
    // TODO: 实现实际的账号验证逻辑
    // 这里应该检查账号是否还有效，是否被封禁等
    
    // 暂时返回成功
    Ok(true)
}

/// 更新账号信息
#[tauri::command]
pub async fn refresh_account_info(
    account_id: String,
    db: State<'_, DatabaseManager>
) -> Result<(), String> {
    info!("Refreshing account info: {}", account_id);
    
    // TODO: 实现实际的账号信息更新逻辑
    // 这里应该通过 API 或爬虫获取最新的粉丝数、关注数等信息
    
    Ok(())
}

/// 获取账号统计信息
#[tauri::command]
pub async fn get_account_stats(
    db: State<'_, DatabaseManager>
) -> Result<serde_json::Value, String> {
    debug!("Fetching account statistics");
    
    match db.get_account_stats().await {
        Ok(stats) => Ok(stats),
        Err(e) => {
            error!("Failed to fetch account stats: {}", e);
            Err(format!("Failed to fetch account stats: {}", e))
        }
    }
}